/*
 * Copyright 2008-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.fsquare.inventory.dao;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.broadleafcommerce.common.persistence.EntityConfiguration;
import org.springframework.stereotype.Repository;

import com.fsquare.inventory.domain.SkuInventory;


@Repository("skuInventoryDao")
public class SkuInventoryDaoImpl implements SkuInventoryDao {
	
	@PersistenceContext(unitName = "blPU")
    protected EntityManager em;

    @Resource(name = "blEntityConfiguration")
    protected EntityConfiguration entityConfiguration;
	
    @Override
	public SkuInventory getInventory(Long skuId) {
    	try{
    		final Query query = em.createNamedQuery("INVENTORY_BY_SKU");
    		query.setParameter("skuId", skuId);
            return (SkuInventory)query.getSingleResult();
    	}catch(NoResultException e){
    		
    	}
        return null;
	}
    
    @Override
    public SkuInventory save(SkuInventory skuInventory) {

//    	SkuInventory response = null;

    	if(skuInventory.getId() == null)
    		em.persist(skuInventory);
        else
        	return em.merge(skuInventory);
    	
    	em.flush();
    	
        return skuInventory;
    }
    
    @Override
    public SkuInventory createSkuInventory() {
    	SkuInventory skuInventory = (SkuInventory) entityConfiguration.createEntityInstance(SkuInventory.class.getName());
        return skuInventory;
    }
	
}
